#!/bin/bash

# 数据库初始化脚本
set -e

echo "开始初始化数据库..."

# 等待数据库启动
echo "等待数据库启动..."
until docker-compose exec -T postgres pg_isready -U videoadmin; do
  echo "数据库未就绪，等待中..."
  sleep 2
done

echo "数据库已就绪，开始创建表..."

# 创建数据库表
docker-compose exec backend alembic upgrade head

echo "数据库表创建完成"

# 创建默认平台模板
echo "创建默认平台模板..."
docker-compose exec -T backend python -c "
from app.db.session import SessionLocal
from app.models.platform_template import PlatformTemplate

db = SessionLocal()

# 检查是否已存在模板
existing = db.query(PlatformTemplate).count()
if existing == 0:
    # 创建默认平台模板
    templates = [
        PlatformTemplate(
            platform_name='douyin_short',
            template_name='douyin_short',
            display_name='抖音短视频',
            description='60秒竖版短视频，适合抖音平台',
            target_duration=60,
            max_segments=8,
            opening_style='dynamic',
            transition_style='cut',
            background_music_style='trending',
            subtitle_style='bold',
            is_active=True,
            is_default=True,
            created_by='system'
        ),
        PlatformTemplate(
            platform_name='xiaohongshu',
            template_name='xiaohongshu',
            display_name='小红书',
            description='45秒生活分享视频，适合小红书平台',
            target_duration=45,
            max_segments=6,
            opening_style='elegant',
            transition_style='fade',
            background_music_style='lifestyle',
            subtitle_style='clean',
            is_active=True,
            is_default=False,
            created_by='system'
        ),
        PlatformTemplate(
            platform_name='bilibili',
            template_name='bilibili',
            display_name='B站',
            description='3分钟内容视频，适合B站平台',
            target_duration=180,
            max_segments=15,
            opening_style='intro',
            transition_style='dissolve',
            background_music_style='background',
            subtitle_style='readable',
            is_active=True,
            is_default=False,
            created_by='system'
        ),
        PlatformTemplate(
            platform_name='weibo_video',
            template_name='weibo_video',
            display_name='微博视频',
            description='30秒快速分享视频，适合微博平台',
            target_duration=30,
            max_segments=5,
            opening_style='quick',
            transition_style='cut',
            background_music_style='viral',
            subtitle_style='highlight',
            is_active=True,
            is_default=False,
            created_by='system'
        )
    ]

    for template in templates:
        db.add(template)

    db.commit()
    print('默认平台模板创建完成')
else:
    print('平台模板已存在，跳过创建')

db.close()
"

echo "数据库初始化完成！"